<?php
declare (strict_types = 1);

namespace app\api\controller;
use app\middleware\Auth;
use app\model\OrderAftersalesModel;
use app\model\OrderItemsModel;
use app\model\OrdersModel;
use app\model\UserFbLogModel;
use EasyWeChat\Factory;
use think\App;
use think\facade\Db;

class OrderAftersales extends Base {

    protected $middleware = [Auth::class];

    private $uid;

    private $order_id;

    private $orderInfo=[];

    private $orderModel;

    private $orderAftersalesModel;

    private $orderItemsModel;

    private $userFbLogModel;

    private $req;


    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->req = request()->param();

        $this->page = isset($this->req['page']) ? $this->req['page'] : 1;

        $this->orderModel = new OrdersModel();

        $this->orderItemsModel = new OrderItemsModel();

        $this->orderAftersalesModel = new OrderAftersalesModel();

        $this->userFbLogModel = new UserFbLogModel();

        $this->order_id = !isset($this->req["order_id"]) ? "" : $this->req["order_id"];

        $this->uid = $this->isLogin();

        addLog("req.txt",json_encode($this->req,256));
    }

    /*
     * 急速退款
     * */
    public function fastRefund(){
        //检查登录
        if(empty($this->order_id)){
            return $this->fail("参数错误：订单号不能为空");
        }

        if(!$this->orderModel->isUserOrder($this->uid,$this->order_id)){
            return $this->fail("订单不存在");
        }

        //如果是联合订单
        if(isUnionOrderId($this->order_id)){

            $p_order_id = $this->order_id;

            if($this->orderAftersalesModel->isRunPorderAftersales($this->order_id)){
                return $this->fail("联合订单已存在售后记录，不可重复申请");
            }

            $ids = $this->orderModel->getOrderByPOrderId($this->order_id);

            foreach ($ids as $id){
                if(!$this->orderModel->isOrderCanFastRefund($id)){
                    return $this->fail("存在不可申请极速退款的订单,无法完成此操作");
                }

                //判断子订单是否存在售后记录
                if($this->orderAftersalesModel->isRunOrderAftersales($id)){
                    return $this->fail("有订单存在售后记录，不可重复申请");
                }
            }

        }else{
            if(!$this->orderModel->isOrderCanFastRefund($this->order_id)){
                return $this->fail("该订单不可申请极速退款");
            }

            //判断是不是存在联合订单的售后记录
            $p_order_id = $this->orderModel->getPOrderIdByOrderId($this->order_id);

            if($this->orderAftersalesModel->isRunPorderAftersales($p_order_id)){
                return $this->fail("联合订单已存在售后记录，不可重复申请");
            }

            //判断是否存在售后记录
            if($this->orderAftersalesModel->isRunOrderAftersales($this->order_id)){
                return $this->fail("订单已存在售后记录，不可重复申请");
            }

        }


        Db::startTrans();

        $p_totalAmout = $this->orderModel->getOrderTotalAmount($p_order_id);

        $totalAmount = $this->orderModel->getOrderTotalAmount($this->order_id);

        $data = [
            "order_id" => $this->order_id,
            "p_order_id" => $this->orderModel->getPOrderIdByOrderId($this->order_id),
            "aftersale_thumbnail"=> "",
            "return_category_id" => 1,
            "aftersale_reason" => "极速退款",
            "aftersale_status"=>3,
            "is_fast"=>1,
            "order_total_amount" =>$totalAmount ,
            "user_refund_amount" => $totalAmount,
            "refund_num" => $this->orderItemsModel->getOrderItemsSpecNum($this->order_id)
        ];

        $orderAftersaleId = $this->orderAftersalesModel->addOne($data);

        $wxPayReturn = $this->wxRefund($data["p_order_id"],$orderAftersaleId,$p_totalAmout,$data['user_refund_amount'],$data['aftersale_reason']);

        if(!$wxPayReturn['res']){
            return  $this->fail($wxPayReturn["msg"]);
        }

        //更新售后订单状态
        $updateOrderAftersaleStatusRes = $this->orderModel->updateOrderAftersaleStatus($this->order_id,3);
        //调用微信退款接口
        $wxReturnInfo = is_array($wxPayReturn["data"]) ? json_encode($wxPayReturn["data"],256) : "";
        //更新接口数据落库
        $orderAftersalesRes = $this->orderAftersalesModel->updateOrderAftersales($orderAftersaleId,["wx_return_info" => $wxReturnInfo]);
        //更新订单状态
        $updateOrderStatusRes = $this->orderModel->updateOrderStatus($this->order_id,-1);

        //根据订单的随缘价扣减福贝
        $fbWhere = [];
        $fbWhere[] =["p_order_id|order_id","=",$this->order_id];
        $fbWhere[] = ["fb_status","=",1];
        $fbLogs = $this->userFbLogModel->where($fbWhere)->select();
        if(!empty($fbLogs)){
            $fbLogSaveData = [];
            foreach ($fbLogs as $log){
                if ($log["fb"] <= 0) {
                    continue; // 跳过非正数记录
                }
                $fbLogSaveData[] = [
                    "uid"=> $this->uid,
                    "fb"=> "-".$log["fb"],
                    "type"=>'order',
                    "p_order_id"=> $log["p_order_id"],
                    "order_id"=> $log["order_id"],
                    "title"=>"极速退款",
                    "description"=>"极速退款，随缘价返还",
                    "fb_status" => 1,
                ];
            }

            $fbRes = $this->userFbLogModel->batchAdd($fbLogSaveData);
        }else{
            $fbRes = true;
        }


        if($orderAftersaleId && $orderAftersalesRes && $updateOrderAftersaleStatusRes && $updateOrderStatusRes && $fbRes ){

            Db::commit();

            return $this->succ("申请成功,退款金额将按照原支付路径返回");

        }else{

            Db::rollback();
            $log =[];
            $log["orderAftersaleId"] = $orderAftersaleId;
            $log["data"] = $data;
            $log["err"] = "微信退款成功，但订单状态更新失败，请联系开发人员解决，请勿重复退款";
            addWxPayLog("wx_return_db_fail.txt",json_encode($log,256));

            return $this->fail("微信退款成功，但订单状态更新失败，数据已记录，请联系开发人员解决，请勿重复退款");
        }
    }




    /*
     * 申请售后
     * */
    public function refund(){

        if(empty($this->order_id)){
            return $this->fail("参数错误：请选择要申请售后的订单");
        }

        //如果是联合订单
        if(isUnionOrderId($this->order_id)){
            $p_order_id = $this->order_id;
            if($this->orderAftersalesModel->isRunPorderAftersales($this->order_id)){
                return $this->fail("联合订单已存在售后记录，不可重复申请");
            }

            $ids = $this->orderModel->getOrderByPOrderId($this->order_id);

            foreach ($ids as $id){

                if(in_array($this->orderModel->getOrderStatus($id),[0,-1]) ){
                    return $this->fail("该订单不可申请售后");
                }

                if(!$this->orderModel->getOrderPayStatus($id)){
                    return $this->fail("该订单未完成支付，不可申请售后");
                }

                //判断子订单是否存在售后记录
                if($this->orderAftersalesModel->isRunOrderAftersales($id)){
                    return $this->fail("有订单存在售后记录，不可重复申请");
                }
            }
        }else{
            //判断是不是存在联合订单的售后记录
            $p_order_id = $this->orderModel->getPOrderIdByOrderId($this->order_id);
            if($this->orderAftersalesModel->isRunPorderAftersales($p_order_id)){
                return $this->fail("联合订单已存在售后记录，不可重复申请");
            }


            if(in_array($this->orderModel->getOrderStatus($this->order_id),[0,-1]) ){
                return $this->fail("该订单不可申请售后");
            }

            if(!$this->orderModel->getOrderPayStatus($this->order_id)){
                return $this->fail("该订单未完成支付，不可申请售后");
            }

            //判断是否存在售后记录
            if($this->orderAftersalesModel->isRunOrderAftersales($this->order_id)){
                return $this->fail("订单已存在售后记录，不可重复申请");
            }
        }


        if(empty($this->req["return_category_id"])){
            return $this->fail("请选择售后类型");
        }

        if(empty($this->req["user_refund_amount"])){
           // return $this->fail("申请的退款金额不能为0");
        }

        $totalAmount = $this->orderModel->getOrderTotalAmount($this->order_id);

        if($this->req["user_refund_amount"] * 100 > $totalAmount){
            return $this->fail("申请的退款金额不能大于订单金额");
        }

        $save = [
            "order_id" => $this->order_id,
            "p_order_id" => $p_order_id,
            "aftersale_thumbnail"=> isset($this->req["aftersale_thumbnail"]) && is_array($this->req["aftersale_thumbnail"]) ? json_encode($this->req["aftersale_thumbnail"],256) : "",
            "return_category_id" => $this->req["return_category_id"],
            "aftersale_reason" =>  isset($this->req["aftersale_reason"]) ? $this->req["aftersale_reason"] : "",
            "aftersale_remark" =>  isset($this->req["aftersale_remark"]) ? $this->req["aftersale_remark"] : "",
            "aftersale_status"=>1,
            "order_total_amount" => $totalAmount,
            "user_refund_amount" => $this->req["user_refund_amount"] * 100,
            "refund_num" =>  isset($this->req["refund_num"]) ? $this->req["refund_num"] : 0 ,
        ];

        Db::startTrans();

        $orderAftersalesRes = $this->orderAftersalesModel->addOne($save);
        $orderUpdateStatusRes = $this->orderModel->updateOrderAftersaleStatus($this->order_id,1);

        $fbRes = true;
        //根据订单的随缘价扣减福贝
        $fbWhere = [];
        $fbWhere[] =["p_order_id|order_id","=",$this->order_id];
        $fbWhere[] = ["fb_status","=",1];
        $fbLogs = $this->userFbLogModel->where($fbWhere)->select();
        if(!empty($fbLogs)) {
            $fbTotalAmount = array_sum(array_column($fbLogs, "fb"));
            $returnFb = intval(($save["user_refund_amount"] / $totalAmount) * $fbTotalAmount);
            if ($returnFb >= $fbTotalAmount) {
                $returnFb = $fbTotalAmount;
            }
            if ($returnFb) {
                $fbRes = $this->userFbLogModel->batchAdd([
                    "uid" => $this->uid,
                    "fb" => "-" . $returnFb,
                    "type" => 'order',
                    "p_order_id" => $p_order_id,
                    "order_id" => $this->order_id,
                    "order_after_sale_id"=>$orderAftersalesRes,
                    "title" => "申请退款",
                    "description" => "申请退款，福贝比例扣减",
                ]);
            }
        }


        if($orderAftersalesRes && $orderUpdateStatusRes && $fbRes){
            Db::commit();
            return $this->succ("申请成功");
        }else{
            Db::rollback();
            return $this->fail("申请失败");
        }

    }


    /*
 * 申请售后
 * */
    public function editRefund(){

        if(!isset($this->req["order_after_sale_id"]) || empty($this->req["order_after_sale_id"])){
            return $this->fail("参数错误：请选择要修改的售后订单");
        }

        if(empty($this->req["return_category_id"])){
            return $this->fail("请选择售后类型");
        }

        if(empty($this->req["user_refund_amount"])){
            // return $this->fail("申请的退款金额不能为0");
        }

        $orderAftersalesInfo = $this->orderAftersalesModel->getInfo($this->req["order_after_sale_id"]);

        if(empty($orderAftersalesInfo)){
            return $this->fail("售后订单不存在");
        }

        if(!in_array($orderAftersalesInfo["aftersale_status"],[-2,-1,0])){
            return $this->fail("售后订单已锁定,不允许修改");
        }

        $totalAmount = $this->orderModel->getOrderTotalAmount($orderAftersalesInfo["order_id"]);

        if($this->req["user_refund_amount"] * 100 > $totalAmount){
            return $this->fail("申请的退款金额不能大于订单金额");
        }

        $save = [
            "aftersale_thumbnail"=> isset($this->req["aftersale_thumbnail"]) && is_array($this->req["aftersale_thumbnail"]) ? json_encode($this->req["aftersale_thumbnail"],256) : "",
            "return_category_id" => $this->req["return_category_id"],
            "aftersale_reason" =>  isset($this->req["aftersale_reason"]) ? $this->req["aftersale_reason"] : "",
            "aftersale_remark" =>  isset($this->req["aftersale_remark"]) ? $this->req["aftersale_remark"] : "",
            "aftersale_status"=>1,
            "order_total_amount" => $totalAmount,
            "user_refund_amount" => $this->req["user_refund_amount"] * 100,
            "refund_num" =>  isset($this->req["refund_num"]) ? $this->req["refund_num"] : 0 ,
        ];



        Db::startTrans();
        $fbRes = true;
        //根据订单的随缘价扣减福贝
        $fbWhere = [];
        $fbWhere[] =["order_after_sale_id","=",$this->req["order_after_sale_id"]];
        $fbWhere[] = ["fb_status","=",0];
        $fbLogs = $this->userFbLogModel->where($fbWhere)->find();
        if(!empty($fbLogs)) {
            $fbTotalAmount = array_sum(array_column($fbLogs, "fb"));
            $returnFb = intval(($save["user_refund_amount"] / $totalAmount) * $fbTotalAmount);
            if ($returnFb >= $fbTotalAmount) {
                $returnFb = $fbTotalAmount;
            }
            if ($returnFb) {
                $fbRes = $this->userFbLogModel->updateAll($fbWhere,[
                    "fb" => "-" . $returnFb
                ]);
            }
        }

        $orderAftersalesRes = $this->orderAftersalesModel->updateOrderAftersales($this->req["order_after_sale_id"],$save);
        $orderUpdateStatusRes = $this->orderModel->updateOrderAftersaleStatus($orderAftersalesInfo["order_id"],1);
        if($orderAftersalesRes && $orderUpdateStatusRes && $fbRes ){
            Db::commit();
            return $this->succ("修改成功");
        }else{
            Db::rollback();
            return $this->fail("修改失败");
        }

    }


    /*
     * 撤销申请
     * */

    public function cancelApply(){
        if(empty($this->req["order_after_sale_id"])){
            return $this->fail("参数错误：order_after_sale_id 不能为空");
        }

        $orderAftersalesInfo = $this->orderAftersalesModel->getInfo($this->req["order_after_sale_id"]);
        if(!$orderAftersalesInfo){
            return $this->fail("售后订单不存在");
        }

        if($orderAftersalesInfo["aftersale_status"] == 3){
            return $this->fail("售后订单已完结，不可撤销");
        }

        if(!empty($orderAftersalesInfo['wx_return_info']) && isset($orderAftersalesInfo['wx_return_info']['return_code']) && $orderAftersalesInfo['wx_return_info']['return_code'] == "SUCCESS"){
            return $this->fail("已有退款成功记录，不可撤销");
        }

        if($orderAftersalesInfo["aftersale_status"] == -1){
            return $this->fail("售后已撤销");
        }

        if(!$this->orderModel->isUserOrder($this->uid,$orderAftersalesInfo["order_id"])){
            return $this->fail("订单不存在");
        }


        $orderAftersalesRes = $this->orderAftersalesModel->updateOrderAftersales($this->req["order_after_sale_id"],["aftersale_status" => -1]);

        $orderUpdateStatusRes = $this->orderModel->updateOrderAftersaleStatus($orderAftersalesInfo["order_id"],0);


        $fbRes = true;
        //根据订单的随缘价扣减福贝
        $fbWhere = [];
        $fbWhere[] =["order_after_sale_id","=",$this->req["order_after_sale_id"]];
        $fbWhere[] = ["fb_status","=",0];
        $fbLogs = $this->userFbLogModel->where($fbWhere)->find();
        if(!empty($fbLogs)) {
            $fbRes = $this->userFbLogModel->where($fbWhere)->delete();
        }

        if($orderAftersalesRes && $orderUpdateStatusRes && $fbRes ){
            Db::commit();
            return $this->succ("申请成功");
        }else{
            Db::rollback();
            return $this->fail("申请失败");
        }
    }



    /*
 * 微信退款
 * */
    private function wxRefund($order_id,$order_after_sale_id,$total_amount,$refund_amount,$reason){
        $wxPayConfig = config("wxpay");
        $wxPayConfig['cert_path'] =  app()->getRootPath().$wxPayConfig['cert_path'];
        $wxPayConfig['key_path'] =  app()->getRootPath().$wxPayConfig['key_path'];

        $log =[];
        $log["order_id"] = $order_id;
        $log["order_after_sale_id"] = (String)$order_id.$order_after_sale_id;
        $log["total_amount"] = $total_amount;
        $log["refund_amount"] = $refund_amount;
        $log["reason"] = $reason;
        try {
            $response = null;
            $app = Factory::payment($wxPayConfig);
            // 调用退款接口
            $response = $app->refund->byOutTradeNumber($order_id, (String)$order_id.$order_after_sale_id, (int)$total_amount, (int)$refund_amount, [
                'refund_desc' => $reason,
                // 其他可选参数
            ]);

            $log["response"] = $response;
            // 处理退款结果
            if ($response['return_code'] === 'SUCCESS' && $response['result_code'] === 'SUCCESS') {
                addWxPayLog("wxpay_refund_success.txt",json_encode($log,256));
                // 退款成功
                return ["res"=>true,"data" => $response];
            } else {
                // 退款失败
                addWxPayLog("wxpay_refund_fail.txt",json_encode($log,256));
                return ["res"=>false,"msg"=>"退款失败：" . $response['err_code_des'],"data" => $response];
            }
        }catch (\Exception $e){
            $log["err"] = $e->getMessage();
            addWxPayLog("wxpay_refund_error.txt",json_encode($log,256));
            return ["res"=>false,"msg"=>"退款异常：" .  $e->getMessage(),"data" => $response];
        }

    }


}
